package org.itheima.controller;

import org.itheima.pojo.Result;
import org.itheima.utils.AliOssUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
public class FileUploadController {

    @PostMapping("/upload")
    public Result<String> fileUpload(@RequestParam("file") MultipartFile file) {
        try {
            // 获取文件的原始文件名
            String originalFilename = file.getOriginalFilename();
            //保证文件名字唯一，防止文件覆盖
            String filename = UUID.randomUUID().toString() + "." + originalFilename.substring(originalFilename.lastIndexOf("."));
            // 构建文件存储路径
            //File dest = new File("E:\\spring-code\\File\\" + filename);
            String url = AliOssUtil.uploadFile(filename,file.getInputStream());
            // 返回成功结果
            return Result.success("图片地址："+url);
        } catch (IOException e) {
            // 处理文件上传异常
            e.printStackTrace();
            return Result.error("文件上传失败");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}